package com.ruoyi.project.system.userSupplyCard.controller;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.code.domain.ShopExpressCode;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.dto.OrderOrderDto;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.userSupplyCard.domain.UserSupplyCard;
import com.ruoyi.project.system.userSupplyCard.dto.UserSupplyCardDto;
import com.ruoyi.project.system.userSupplyCard.service.IUserSupplyCardService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.userSupplyLog.domain.UserSupplySendLog;
import com.ruoyi.project.system.userSupplyLog.service.IUserSupplySendLogService;

/**
 * 用户供应Controller
 * 
 * @author f_baisi
 * @date 2020-07-20
 */
@Controller
@RequestMapping("/system/userSupplyCard")
public class UserSupplyCardController extends BaseController
{
    private String prefix = "system/userSupplyCard";

    @Autowired
    private IUserSupplyCardService userSupplyCardService;
    @Autowired
    private IUserSupplySendLogService userSupplySendLogService;

    @RequiresPermissions("system:userSupplyCard:view")
    @GetMapping()
    public String userSupplyCard()
    {
        return prefix + "/userSupplyCard";
    }

    /**
     * 查询用户供应列表
     */
    @RequiresPermissions("system:userSupplyCard:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(UserSupplyCard userSupplyCard)
    {
        startPage();
        List<UserSupplyCardDto> list = userSupplyCardService.selectUserSupplyCardList(userSupplyCard);
        return getDataTable(list);
    }

    /**
     * 导出用户供应列表
     */
    @RequiresPermissions("system:userSupplyCard:export")
    @Log(title = "用户供应", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(UserSupplyCard userSupplyCard)
    {
        List<UserSupplyCardDto> list = userSupplyCardService.selectUserSupplyCardList(userSupplyCard);
        ExcelUtil<UserSupplyCardDto> util = new ExcelUtil<UserSupplyCardDto>(UserSupplyCardDto.class);
        return util.exportExcel(list, "userSupplyCard");
    }

    /**
     * 新增用户供应
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存用户供应
     */
    @RequiresPermissions("system:userSupplyCard:add")
    @Log(title = "用户供应", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UserSupplyCard userSupplyCard)
    {
        return toAjax(userSupplyCardService.insertUserSupplyCard(userSupplyCard));
    }

    /**
     * 修改用户供应
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        UserSupplyCard userSupplyCard = userSupplyCardService.selectUserSupplyCardById(id);
        mmap.put("userSupplyCard", userSupplyCard);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户供应
     */
    @RequiresPermissions("system:userSupplyCard:edit")
    @Log(title = "用户供应", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(UserSupplyCard userSupplyCard)
    {
        return toAjax(userSupplyCardService.updateUserSupplyCard(userSupplyCard));
    }

    /**
     * 删除用户供应
     */
    @RequiresPermissions("system:userSupplyCard:remove")
    @Log(title = "用户供应", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(userSupplyCardService.deleteUserSupplyCardByIds(ids));
    }


    /**
     * 查询订单发货详情
     */
    @GetMapping("/send/{id}")
    public String send(@PathVariable String id,ModelMap map)
    {
        map.put("id",id);
        return prefix + "/send";
    }
    /**
     * 供应单发货
     */
    @PostMapping("/send")
    @ResponseBody
    public AjaxResult supplySend(UserSupplySendLog userSupplySendLog)
    {
        UserSupplyCard userSupplyCard = this.userSupplyCardService.selectUserSupplyCardById(userSupplySendLog.getUserSupplyId());
        if(userSupplyCard==null){
            return AjaxResult.error("找不到供应单");
        }

        UserSupplySendLog select = new UserSupplySendLog();
        select.setUserSupplyId(userSupplySendLog.getUserSupplyId());
        List<UserSupplySendLog> userSupplySendLogs = this.userSupplySendLogService.selectUserSupplySendLogList(select);
        userSupplySendLog.setNum(userSupplySendLogs.size()+1);
        userSupplySendLog.setCreated(DateUtils.getNowDate());
        this.userSupplySendLogService.insertUserSupplySendLog(userSupplySendLog);
        //更新供应单信息
        UserSupplyCard update = new UserSupplyCard();
        update.setId(userSupplyCard.getId());
        Integer sum = userSupplyCard.getSendTotal()+userSupplySendLog.getTotal();
        //判断是否已配送够数
        if(sum>=userSupplyCard.getTotal()){
            update.setStatus(1);
        }
        update.setSendTotal(sum);
        this.userSupplyCardService.updateUserSupplyCard(update);
        return AjaxResult.success();
    }

    @GetMapping("/showlog/{id}")
    public String showlog(@PathVariable String id,ModelMap map)
    {
        map.put("id",id);
        return prefix + "/showLog";
    }

    /**
     * 查询商品列表
     */
    @PostMapping("/showlog")
    @ResponseBody
    public TableDataInfo showLogList(UserSupplySendLog userSupplySendLog)
    {
        startPage();
        List<UserSupplySendLog> list = this.userSupplySendLogService.selectUserSupplySendLogList(userSupplySendLog);
        return getDataTable(list);
    }

    @PostMapping("/importExcel")
    @Log(title = "供应卡", businessType = BusinessType.UPDATE)
    @ResponseBody
    @Transactional
    public R supplyCardImport(MultipartFile file){
        if(file!= null) {
            String userExcelFileName = file.getOriginalFilename();
            //判断是否是Excel文件
            if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
            {
                importExcel(file, userExcelFileName);
                return R.ok();
            }
            return R.error("文件类型错误");
        }
        return R.error("请选择文件");
    }


    public void importExcel(MultipartFile file, String excelFileName) {
        //1.创建输入流
        try {
            //FileInputStream inputStream = new FileInputStream(file);
            //boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
            //1.读取工作簿
            boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
            Workbook workbook = is03Excel?new HSSFWorkbook(file.getInputStream()):new XSSFWorkbook(file.getInputStream());
            //Workbook workbook = new HSSFWorkbook(file.getInputStream());
            //2.读取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //3.读取行
            //判断行数大于一,是因为数据从第二行开始插入

            if(sheet.getPhysicalNumberOfRows() > 1) {
                //跳过前一行
                for(int k=1;k<sheet.getPhysicalNumberOfRows();k++ ) {
                    //读取单元格
                    Row row0 = sheet.getRow(k);
                    //供应卡编号
                    Cell cell0 = row0.getCell(0);
                    String supplyNo =cell0.getStringCellValue().replace("\t","").trim();
                    //配送人名称
                    String username = "";
                    Cell cell9 = row0.getCell(1);
                    if (cell9 == null) {
                        username = "";
                    } else {
                        cell9.setCellType(Cell.CELL_TYPE_STRING);
                        username = cell9.getStringCellValue().replace("\t","").trim();
                    }
                    //配送人电话
                    String mobile = "";
                    Cell cell10 = row0.getCell(2);
                    if (cell10 == null) {
                        mobile = "";
                    } else {
                        cell10.setCellType(Cell.CELL_TYPE_STRING);
                        mobile = cell10.getStringCellValue().replace("\t","").trim();
                    }
                    //配送数量
                    Integer total;
                    Cell cell1 = row0.getCell(3);
                    if (cell9 == null) {
                        total = null;
                    } else {
//                        total = Integer.parseInt(cell1.getStringCellValue().replace("\t","").trim());
                        total= Double.valueOf(cell1.getNumericCellValue()).intValue();
                    }
                    //单号查询供应卡信息
                    UserSupplyCard byNo = this.userSupplyCardService.findByNo(supplyNo);
                    UserSupplyCard update = new UserSupplyCard();
                    update.setId(byNo.getId());
                    update.setSendTotal(byNo.getSendTotal()+total);
                    if(byNo.getTotal()<=update.getSendTotal()){
                        update.setStatus(1);
                    }
                    this.userSupplyCardService.updateUserSupplyCard(update);
                    //查询供应卡下的配送信息
                    UserSupplySendLog select = new UserSupplySendLog();
                    select.setUserSupplyId(byNo.getId());
                    List<UserSupplySendLog> userSupplySendLogs = this.userSupplySendLogService.selectUserSupplySendLogList(select);
                    UserSupplySendLog userSupplySendLog = new UserSupplySendLog();
                    userSupplySendLog.setUserSupplyId(byNo.getId());
                    userSupplySendLog.setNum(userSupplySendLogs.size()+1);
                    userSupplySendLog.setMobile(mobile);
                    userSupplySendLog.setTotal(total);
                    userSupplySendLog.setUsername(username);
                    userSupplySendLog.setCreated(DateUtils.getNowDate());
                    this.userSupplySendLogService.insertUserSupplySendLog(userSupplySendLog);
                }
            }
            workbook.close();
            //inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
